# -*- coding:utf-8 -*-
import json
from flask import current_app, g
from app.tools.timestamp import dealine
from app.tools.message import message
from app.tools.log import log
from app.views.risk.application import application as main
from app.models.risk_manage import Risk_Flow, Risk_Application as RA, RiskPicture
from app.tools.permission import permission
from app.tools.number import get_number
from app.tools.redis_op import Operator

from .. import *

op = Operator()


def signin_required():
    if not current_user.is_authenticated:
        return redirect(url_for('auth.login'))


main.before_request(signin_required)


@main.before_request
@login_required
@permission(['service', 'director', 'manage', 'finance', 'review', 'admin', 'super'])
def check_permission():
    g.kw = {}
    return


def update_xfrs():
    import uuid
    xfrs = str(uuid.uuid4())
    op.hset('xfrs', xfrs, 0)
    return xfrs


roles = {'service': u'客服部', 'manage': u'综合管理部', 'review': u'车辆审批部', 'finance': u'财务部',
         'hr': u'人资行政部', 'admin': u'管理层', 'director': u'客服主管', 'upload': u'业务上传',
         'setup': u'网站设置', 'super': u'超级管理员'}

dy = RiskPicture.DY_DICT.get('app')
zy = RiskPicture.ZY_DICT.get('app')
sort_dy = sorted(dy.iteritems(), key=lambda asd: asd[0])
sort_zy = sorted(zy.iteritems(), key=lambda asd: asd[0])


def save_pictures(flow_id, pledge_type, pics):
    flow = u'app'
    a = len('photos_xx')
    domain = current_app.config['QINIU_DOMAIN']
    for k, v in pics.items():
        num = k[a:]  # 取出数字
        for pic_name in v:
            url = domain + pic_name
            form = dict(
                pledge_type=pledge_type,
                flow_id=flow_id,
                url=url,
                flow=flow,
                picture_type=num
            )
            rp = RiskPicture(**form)
            rp.save()


def has_picture(form, pledge_type):  # 判断有没有图片
    if pledge_type == u'抵押（GPS）':
        prefix = 'photos_dy'
        dit = dy
    elif pledge_type == u'质押（转移）':
        prefix = 'photos_zy'
        dit = zy
    else:
        return False
    pics = {}
    for i in dit:
        key = prefix + i
        try:
            pic_list = json.loads(form.get(key, ''))
        except ValueError:
            return False
        if len(pic_list) == 0:
            return False
        pics[key] = pic_list
    return pics


@main.route('/launch')  # 发起申请
def launch():
    role = session['role']
    if role in ('finance', 'manage', 'review',):
        return redirect(url_for('.lists'))
    xfrs = update_xfrs()
    area = session.get('area')
    sort_dy = sorted(dy.iteritems(), key=lambda asd: asd[0])
    sort_zy = sorted(zy.iteritems(), key=lambda asd: asd[0])
    return render_template('risk/application/launch.html',
                           area=area,
                           xfrs=xfrs,
                           sort_dy=sort_dy,
                           sort_zy=sort_zy,
                           )


@main.route('/p_launch', methods=['POST'])
def p_launch():
    form = request.form
    if session['role'] not in ('service', 'admin', 'director'):
        return jsonify(dict(
            success=False,
            message=u'不是客服或管理员，不能发起申请'
        ))
    pledge_type = form.get('pledge_type', '')
    pics = has_picture(form, pledge_type)
    if not pics:
        return jsonify(dict(
            success=False,
            message=u'图片上传不全'
        ))
    xfrs = form.get('xfrs', '')

    if xfrs in op.r.hkeys('xfrs'):
        op.r.hdel('xfrs', xfrs)
        ra = RA(form)
        flow_id = get_number('DK')  # 生成一个流程单号
        staff_number = session['staff_number']
        name = session['name']
        ra.flow_id = flow_id
        ra.initiator = staff_number
        if session['role'] in ('admin',):
            ra.review_status = 'admin'
            role_list = ['admin']
            next_name = u'管理层'
        else:
            ra.review_status = 'review'
            role_list = ['review']
            next_name = u'车辆审核部'
        ra.flow_status = u'申请'

        # 处理图片
        save_pictures(flow_id, pledge_type, pics)

        ra.save()

        rf = dict(
            flow_id=flow_id,
            review=staff_number,
            review_name=session['name'],
        )
        rf = Risk_Flow(**rf)
        rf.save()
        log(u'申请流程 {} 已由 【{}】 发起'.format(flow_id, name))
        url = url_for('.detail', id=ra.id)
        msg = u'申请流程 <a target="_blank" href="{}">{}</a> 已由 【{}】 发起，待 【{}】 审核'.format(url, flow_id, name, next_name)
        message(msg, u'审核', role_list=role_list)  # 发消息
        return jsonify(dict(
            success=True,
            message=u'发起申请流程成功！',
            next=url_for('.launch')
        ))
    return jsonify(dict(
        success=False,
        message=u'页面已过期，请刷新后重试'
    ))


@main.route('/lists')
@permission(['director', 'manage', 'finance', 'review', 'admin', 'super'])
def lists():
    return render_template('risk/application/list.html')


@main.route('/get_list')  # 带审、拒绝列表（申请）
def get_list():
    values = request.values
    limit = int(values.get('limit', '10'))
    offset = int(values.get('offset', '0'))
    list_type = request.values.get('list_type')
    number = values.get('number')
    start = values.get('start')
    end = values.get('end')
    submitter = values.get('submitter')
    area = values.get('area')
    search_type = values.get('search_type')
    tb_name = values.get('tb_name')  # 前端页面中多个表格共用同一组搜索参数，tb_name用于标识当前是哪一个表格在使用这些参数
    try:
        f = '%Y/%m/%d'
        end = datetime.datetime.strptime(end, f)
        dt = end + datetime.timedelta(days=1)  # 需要加一天才可以搜索到原本的end指定的日期
        end = dt.strftime(f)
    except ValueError:
        return jsonify({'state': 1, 'msg': u'参数错误'})
    result = RA.query

    if tb_name == list_type and search_type != '5':  # 5代表重置搜索，即不考虑搜索条件；tb_name用于检查当前的搜索参数是否与表格相对应
        if search_type == '0':
            g.kw['flow_id'] = number
        if search_type == '1' or search_type == '4':
            g.kw['person_type'] = submitter
        if search_type == '2' or search_type == '4':
            result = result.filter(RA.area.like('%' + area + '%'))
        if search_type == '3' or search_type == '4':
            result = result.filter(RA.timestamp_app.between(start, end))

    if list_type == 'to_review':
        g.kw['flow_status'] = u'申请'
        g.kw['review_status'] = session['role']
    elif list_type == 'rejected':
        g.kw['review_status'] = u'申请已拒绝'
    else:
        return jsonify({'state': 1, 'msg': u'参数错误'})

    result = result.filter_by(**g.kw)
    s = result.order_by(RA.timestamp_app.desc()). \
        paginate(offset / limit + 1, limit, False)
    result = s.items
    count = s.total
    data = []

    for item in result:
        detail_url = url_for('.detail', id=item.id)
        r = Risk_Flow.query.filter_by(flow_id=item.flow_id). \
            order_by(Risk_Flow.timestamp.desc()).first()
        data.append({
            'id': item.id,
            'flow_id': item.flow_id,
            'pledge_type': item.pledge_type,
            'amount': item.amount,
            'days': item.days,
            'area': item.area,
            'name': item.name + '(' + item.person_type + ')',
            'initiator': item.initiator,
            'review': r.review,
            'timestamp': item.timestamp_app,
            # 'operate': '<a href="' + detail_url + '">审核</a>',
            'operate': detail_url,
        })
    json = {'total': count, 'rows': data}
    return jsonify(json)


@main.route('/detail/<id>')  # （审批）申请详情
def detail(id):
    r = RA.query.get(id)
    xfrs = update_xfrs()
    # if not r.review_status == session['role']:  # 判断当前员工 是否属于下一审核部门  # or (r.initiator == session['staff_number'])
    #     return render_template('404.html'), 404
    flow_id = r.flow_id
    pledge_type = r.pledge_type

    if pledge_type == u'抵押（GPS）':
        dit = dy
    else:
        dit = zy
    sort_dit = sorted(dit.iteritems(), key=lambda asd: asd[0])  # 把图片类型和标题 排序，传给模板
    rps = RiskPicture.query.filter_by(flow_id=flow_id).order_by(RiskPicture.picture_type).all()  # 查询该流程的图片
    rfs = Risk_Flow.query.filter_by(flow_id=flow_id).order_by(Risk_Flow.timestamp).all()  # 查询审核过程
    finished = True
    if r.flow_status == u'申请' and r.review_status == session['role']:
        finished = False

    return render_template('risk/application/detail.html',
                           r=r,
                           finished=finished,
                           rps=rps,
                           dit=dit,
                           rfs=rfs,
                           sort_dit=sort_dit,
                           xfrs=xfrs)


@main.route('/review/pass', methods=['POST'])  # 审批申请 (通过)
def app_pass():
    form = request.form
    xfrs = form.get('xfrs', '')
    id = form.get('id', '')
    if xfrs in op.r.hkeys('xfrs'):
        op.r.hdel('xfrs', xfrs)
        flow_id = form.get('flow_id', '')
        r = RA.query.filter_by(flow_id=flow_id).first()
        review_name = session['name']
        if r.review_status == u'未审':
            r.review_status = 'review'
        elif r.review_status == 'review':
            r.review_status = 'manage'
        elif r.review_status in ('manage', 'admin'):
            r.review_status = u'待发起放款'
            r.flow_status = u'待放款'
        r.save()

        rf = dict(
            flow_id=flow_id,
            review=session['staff_number'],
            review_name=review_name,
        )
        rf = Risk_Flow(**rf)
        rf.save()
        url = url_for('loan.launch', flow_id=flow_id)
        msg = u'申请流程 <a target="_blank" href="{}">{}</a> 已由 【{}】 通过'.format(url, flow_id, review_name)

        log(msg)
        message(msg, u'审核', server_id=r.initiator)  # 发消息
        flash(u'操作成功！')

        return redirect(url_for('.lists'))
    else:
        flash(u'操作失败，请重试！')
        return redirect(url_for('.detail', id=id))


@main.route('/review/reject', methods=['POST'])  # 审批申请 (拒绝)
def app_reject():
    form = request.form
    xfrs = form.get('xfrs', '')
    if xfrs in op.r.hkeys('xfrs'):
        op.r.hdel('xfrs', xfrs)
        flow_id = form.get('flow_id', '')
        r = RA.query.filter_by(flow_id=flow_id).first()
        r.review_status = u'申请已拒绝'
        r.flow_status = u'申请已完结'
        r.save()
        review_name = session['name']
        rf = dict(
            flow_id=flow_id,
            review=session['staff_number'],
            review_name=review_name,
        )
        rf = Risk_Flow(**rf)
        rf.save()
        log(u'审批申请流程-拒绝：{}'.format(flow_id))
        url = url_for('.detail', id=r.id)
        msg = u'申请流程 <a target="_blank" href="{}">{}</a> 已由 【{}】 拒绝'.format(url, flow_id, review_name)
        message(msg, u'审核', server_id=r.initiator)  # 发消息
        flash(u'操作成功！')
        return redirect(url_for('.lists'))
    else:
        flash(u'操作失败，请重试！')
        return redirect(url_for('.detail', id=id))
